package com.baipeng.bp_alicloud_push.application;

import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.HonorRegister;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.MeizuRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;

import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;

public class PushApplication extends Application {
    private static final String TAG = "MPS:Init";

    /**
     * 初始化云推送通道
     */
    public void initCloudChannel(Application application, String channelId, String channelName, String channelDesc) {
        // 创建notificaiton channel
        this.createNotificationChannel(channelId, channelName, channelDesc);

        Context applicationContext = application.getApplicationContext();
        PushServiceFactory.init(applicationContext);
        final CloudPushService pushService = PushServiceFactory.getCloudPushService();
//        pushService.setLogLevel(CloudPushService.LOG_DEBUG);
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.i(TAG, "init cloudchannel success");
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }

    private void createNotificationChannel(String channelId, String channelName, String channelDesc) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "1";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "notification channel";
            // 用户可以看到的通知渠道的描述
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
            // 配置通知渠道的属性
            mChannel.setDescription(channelDesc);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }

    /**
     * 辅助通道集成
     */
    public void register(Application application, String xiaomiId, String xiaomiKey, String oppoAppKey, String oppoAppSecret, String meizuAppId, String meizuAppKey) {
        Context applicationContext = application.getApplicationContext();

        try {
            String packageName = getPackageName();
            PackageManager packageManager = getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            String huawei_appid = applicationInfo.metaData.getString("huawei_appid", "");
            String honor_appid = applicationInfo.metaData.getString("honor_appid", "");
            String vivo_apikey = applicationInfo.metaData.getString("vivo_apikey", "");
            String vivo_appid = applicationInfo.metaData.getString("vivo_appid", "");

            if (!huawei_appid.isEmpty()) {
                Log.i(TAG, "huawei_appid=" + huawei_appid);
                HuaWeiRegister.register(application);
            }
            if (!honor_appid.isEmpty()) {
                Log.i(TAG, "honor_appid=" + honor_appid);
                HonorRegister.register(application);
            }
            if (!vivo_apikey.isEmpty() && !vivo_appid.isEmpty()) {
                Log.i(TAG, "vivo_apikey=" + vivo_apikey);
                Log.i(TAG, "vivo_appid=" + vivo_appid);
                VivoRegister.register(applicationContext);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "applicationInfo metaData =" + e.getLocalizedMessage());
            e.printStackTrace();
        }

        if (!xiaomiId.isEmpty() && !xiaomiKey.isEmpty()) {
            MiPushRegister.register(applicationContext, xiaomiId, xiaomiKey);
        }

        if (!oppoAppKey.isEmpty() && !oppoAppSecret.isEmpty()) {
            OppoRegister.register(applicationContext, oppoAppKey, oppoAppSecret);
        }
        if (!meizuAppId.isEmpty() && !meizuAppKey.isEmpty()) {
            MeizuRegister.register(applicationContext, meizuAppId, meizuAppKey);
        }
    }

    public static MethodChannel methodChannel;
    public static EventChannel.EventSink eventSink = null;

    public static void onNotification(Object obj) {
        if (methodChannel != null && obj != null) {
            methodChannel.invokeMethod("receiver", obj);
        }
        if (eventSink != null && obj != null) {
            eventSink.success(obj);
        }
    }
}
